package cn.biplam.front.component.view.systemManage.task.runmanage;

import java.util.ArrayList;

import cn.biplam.common.client.Log;
import cn.biplam.common.client.OperatorResult;
import cn.biplam.common.client.Log.Log_Level;
import cn.biplam.common.runtime.Task;
import cn.biplam.common.runtime.TaskBase;
import cn.biplam.common.tools.TOOLS;
import cn.biplam.common.wrapper.D2KArray;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.UserInfo;
import cn.biplam.front.component.AjxResponse;
import cn.biplam.front.component.data.common.CaptionComp;
import cn.biplam.front.html.HtmlDiv;
import cn.biplam.front.html.HtmlText;
import cn.biplam.front.html.base.HtmlWindow;
import cn.biplam.front.template.control.FlatTable;
import cn.biplam.front.template.control.FlowTable;
import cn.biplam.front.template.control.table.TablePropertys;
import cn.biplam.front.template.pageFrame.mdManage.MdObject;
import cn.biplam.front.template.pageFrame.mdManage.MdPage;

/**
 * 任务管理-运行管理主页面
 * <li>显示正在运行的任务
 * <li>对正在运行的任务可以中止当前任务的运行
 * @author WangSong 2009-7-16下午02:02:23
 * @version 1.0
 */
public class RunManage extends AjxResponse {

	public static final String cId="8802";
	public static final String aId_Main="880201";
	public static final String aId_Stop="880202";
	
	@Override
	protected HtmlWindow ajxGet() throws ErrorMessage {
		
		if(aId_Main.equals(actionId)){
			return getMainPage();
		}if(aId_Stop.equals(actionId)){
			return getTaskStop();
		}else{
			throw new ErrorMessage("RunManage.java action is not found:"+actionId);
		}
	}
	
	private HtmlWindow getMainPage() throws ErrorMessage{
		MdPage mp = new MdPage(cId,sHomeUrl,mUser);
		/** 设置界面标题 */
		mp.setTitleDesc(CaptionComp.get(mUser, "282"));
		/** 设置界面标题logo */
		mp.setTitleLogo("/images/t_rt.gif");
		/** 设置管理内容*/
		MdObject mo = new MdObject(cId);
		mo.putTable(get(mUser));
		mp.putManage(mo.get());
		return mp.get();
	}
	
	/**
	 * 线程停止
	 * @return
	 * @throws ErrorMessage 
	 */
	private HtmlWindow getTaskStop() throws ErrorMessage{
		if(recordId!=null){
			/**中断当前线程*/
			Task.stopTask(recordId);
			/**判断线程是否已经中断*/
			while(Task.getTask(recordId)!=null){
				try{
					Thread.sleep(1000);
				}catch (Exception e) {
					Log.write("中断任务"+recordId+"异常!", Log_Level.Warnning);
				}
			}
		}
		return getMainPage();
	}
	
	/**
	 * 运行管理主页面
	 * @param mUser
	 * @return
	 * @throws ErrorMessage 
	 */
	private HtmlWindow get(UserInfo mUser) throws ErrorMessage{
		HtmlWindow runManage = new HtmlDiv();
		
		OperatorResult data = this.getRunTasks();
		if(data!=null && data.size()>0){
			/** 表主键 */
			String mainKey="name";
			/** 表格列对应字段名 */
			String[] tableFields={"name","desc","startTime","runTimeLength","operator"};
			/** 表格列类型 */
			TablePropertys.Col_Content_Type[] fieldsType={
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.BUTTON
			};
			/** 设置列标题 */
			String[] tableColTitles={"任务名称","任务描述","开始时间","运行时长","操作"};
			TablePropertys property=new TablePropertys(tableFields,fieldsType,tableColTitles,sHomeUrl,mUser);
			/**设置按钮*/
			setOperator(property);
			
			/** 创建表对象 */
			FlowTable st=new FlowTable(cId,mainKey,property); 
			/** 将数据集放入表格 */
			st.put(data);
			st.setWidth("800");
			
			runManage.put(st.get());
			runManage.bind(refresh());
		}else{
			FlatTable ft=new FlatTable(cId,"");
			HtmlWindow text =new HtmlText(null,null,"无正在运行的任务");
			text.setStyle("text-align","center");
			ft.putTh("任务名称",0,0);
			ft.putTh("任务描述",0,1);
			ft.putTh("开始时间",0,2);
			ft.putTh("运行时长",0,3);
			ft.putTh("操作",0,4);
			ft.putTd(text, 1, 0,"5","4");
			runManage.put(ft.get());
		}
		
		return runManage;
	}
	
	/**
	 * 设置按钮
	 * @param property  表格属性对象
	 * @throws ErrorMessage
	 */
	private void setOperator(TablePropertys property) throws ErrorMessage{
		/** 设置按钮回调对象*/
		property.setCallBack("operator", new RunManageOperatorCallBack());
	}
	
	/**
	 * 取正在运行任务信息
	 * @return
	 * @throws ErrorMessage
	 */
	private OperatorResult getRunTasks() throws ErrorMessage{
		ArrayList<String> d2kArr = new ArrayList<String>();
		d2kArr.add("name");
		d2kArr.add("desc");
		d2kArr.add("startTime");
		d2kArr.add("runTimeLength");
		D2KArray<String> data = new D2KArray<String>(d2kArr);
		Thread[] list = getRunTask();
		String[] value = null;
		TaskBase tb = null;
		for(int i=0;i<list.length;i++){
			tb = Task.getTask(list[i].getName());
			value = new String[]{tb.getName(),
					             TOOLS.stringNullToEmpty(tb.getComment()),
					             TOOLS.stringNullToEmpty(tb.getStartTime()),
					             TOOLS.stringNullToEmpty(tb.getTimeLen())};
			data.put(value);
		}
		OperatorResult or = new OperatorResult();
		or.setD2ArrayResult(data);
		return or;
	}
	
	/**
	 * 取正在运行任务线程
	 * @return
	 */
	private Thread[] getRunTask(){
		
		ThreadGroup tg = Task.get();
		Thread[] list = new Thread[tg.activeCount()];
		tg.enumerate(list);
		return list;
	}
	
	/**
	 * 刷新脚本
	 * @param taskId 任务ID
	 * @return 刷新脚本字符串
	 */
	private String refresh(){
		StringBuilder sb = new StringBuilder();
		sb.append("if(true){");
		sb.append(" setTimeout(\"a('"+cId+"','"+RunManage.aId_Main+"','refresh')\",5000);");
		sb.append("};");		
		return sb.toString();
	}
	
}
